package XishiBackend.base;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import XishiBackend.models.entity.Order;
import XishiBackend.models.repository.OrderRepository;

@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
    @Autowired
    private OrderRepository oR;
    
    @Scheduled(cron = "0 */1 *  * * * ")
    public void cancelOutTimeOrder(){
        List<Order> list = oR.findByHasPaid(Constant.NOT_PAID);
        for(Order o:list) {
            long createTime = TimeUtil.string2Date(o.getCreateTime()).getTime();
            long now = TimeUtil.nowLong();
            if(now - createTime > 2 * 3600 * 1000) {
                o.setOperatorId(99999L);
                o.setUpdateTime(TimeUtil.now());
                o.setHasPaid(Constant.PAID);
                o.setStatus(Constant.CANCEL);
                o.setCancelRemark(Constant.NOTPAY_CANCEL);
            }
        }
        oR.save(list);
    }

    @Scheduled(cron = "0 55 0  * * * ")
    public void cancelLastDayOrder(){
        //取得相应订单
        List<Order> list = oR.findByStatus(Constant.NEW);
        list.addAll(oR.findByStatus(Constant.DELIVERY));
        //将订单取消
        for(Order o:list) {
            o.setOperatorId(99999L);
            o.setStatus(Constant.CANCEL);
            o.setCancelRemark(Constant.NEXTDAY_CANCEL);
            o.setUpdateTime(TimeUtil.now());
//            if(o.getOrderType() == Constant.WX_ONLINE && o.isHasPaid() == Constant.NOT_PAID) {
//                //如果是没有付过款的微信订单，就调用关闭订单接口
//                String resp = Constant.wxCloseOrder(o);
//                JSONObject json = JSONObject.fromObject(resp);
//                if(!json.getString("return_code").equals("SUCCESS")) {
//                    System.out.println(json.getString("return_msg")+":"+o.getOrderId());
//                }
//            }
        }
        oR.save(list);
        System.out.println("完成将隔夜订单置为取消状态，订单数："+list.size());
    }
}
